package com.pp.tourism.web.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.pp.tourism.web.dto.ApiResponse;
import com.pp.tourism.web.pojo.User;
import com.pp.tourism.web.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PutMapping("/queryAll")
    public ApiResponse queryAllUsers(){
        try {
            return ApiResponse.ok(userService.selectList(null));
        }catch (Exception e){
            e.printStackTrace();
            return ApiResponse.error("500", "查询失败！");
        }
    }

    @PutMapping("/queryUserById")
    public ApiResponse queryUserById(@RequestBody  Map<String,Object> param){
        try {
            Integer id = MapUtils.getInteger(param, "id");
            if(id == null )throw new RuntimeException("id不能为空");
            return ApiResponse.ok(userService.selectById(id));
        }catch (RuntimeException e){
            e.printStackTrace();
            return ApiResponse.error("500", e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return ApiResponse.error("500", "查询失败！");
        }

    }

    @PutMapping("/queryUsers")
    public ApiResponse queryUsers(@RequestBody Map<String,Object> param, HttpSession session){
        /*for (String key : param.keySet()) {
            System.out.println("key= "+ key + " and value= " + param.get(key));
        }*/
        try {
            List<User> users = userService.queryUsers(param);
            for (User u:users) {
                session.setAttribute("username",u.getUsername());
            }
            return ApiResponse.ok(users);
        }catch (Exception e){
            e.printStackTrace();
            return ApiResponse.error("500", "查询失败！");
        }
    }

    @PutMapping("/queryUserPage")
    @ApiOperation("分页查询用户")
    public ApiResponse queryUserPage(@RequestBody Map<String,Object> param){
        try {
            Page<User> userPage = userService.queryUserPage(param);
            return ApiResponse.ok(userPage);
        }catch (Exception e){
            e.printStackTrace();
            return ApiResponse.error("500", "查询失败！");
        }
    }

}
